<template>
  <div class="construction">
    <el-row>
      <el-col :span="6">
        <el-form ref="form"
                 label-width="80px"
                 :model="projectNameList">
          <el-form-item label="项目名称">
            <el-select v-model="projectNameList.value"
                       placeholder="请选择项目名称"
                       class="select-style"
                       :disabled="projectNameList.options.length === 1 ? true :false"
                       @change="selectProjectNameList">
              <el-option v-for="item in projectNameList.options"
                         :key="item.value"
                         :label="item.label"
                         :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-col>

      <el-col :span="24">
        <el-button type="primary"
                   @click="editSchemeDialog('create', {})">添加施工升降机</el-button>
      </el-col>
      <el-col :span="24">
        <el-table :data="tableData.list"
                  style="width: 100%; margin-top: 20px"
                  :header-cell-style="{ background: '#eee' }"
                  height="550px">
          <el-table-column type="index"
                           width="100"
                           label="序号"
                           align="center">
          </el-table-column>
          <el-table-column prop="device_name"
                           label="设备名称"
                           align="center">
          </el-table-column>
          <el-table-column prop="device_no"
                           label="设备编号"
                           align="center">
          </el-table-column>
          <el-table-column prop="online"
                           label="设备状态"
                           align="center">
          </el-table-column>
          <el-table-column prop="installation_date"
                           label="安装日期"
                           align="center">
            <template slot-scope="scope">
              {{ getInstallDate(scope.row.installation_date) }}
            </template>
          </el-table-column>
          <el-table-column label="操作"
                           align="center">
            <template slot-scope="scope">
              <el-button type="text"
                         @click="editSchemeDialog('view', scope.row)">查看</el-button>
              <el-button type="text"
                         @click="editSchemeDialog('edit', scope.row)">编辑</el-button>
              <el-button type="text"
                         @click="delet(scope.row)">删除</el-button>
              <el-button type="text"
                         @click="onRealTimeData(scope.row)">实时数据</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-pagination @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   :current-page="requestparam.pageNum"
                   :page-size="requestparam.pageSize"
                   :page-sizes="[10, 20, 30, 40]"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="tableData.total_count">
    </el-pagination>
    <el-dialog :title="title"
               @close="dialogClose"
               :visible.sync="dialogVisible">
      <el-form :model="editSchemeData"
               :rules="rules"
               ref="ruleForm"
               label-width="100px"
               class="demo-ruleForm">
        <el-form-item label="项目名称"
                      prop="projectName">
          <el-input v-model="editSchemeData.projectName"
                    :disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item label="设备名称"
                      prop="deviceName">
          <el-input v-model="editSchemeData.deviceName"
                    :disabled="view"></el-input>
        </el-form-item>
        <el-form-item label="设备编号"
                      prop="deviceNo">
          <el-input v-model="editSchemeData.deviceNo"
                    :disabled="view"></el-input>
        </el-form-item>
        <el-form-item label="安装日期"
                      prop="installationDate">
          <el-date-picker v-model="editSchemeData.installationDate"
                          type="date"
                          placeholder="选择日期"
                          :disabled="view">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="Cancel">取 消</el-button>
        <el-button type="primary"
                   @click="editScheme">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { constructionLiftApi } from "@/services/WorkCenter";
import { ProjectListApi } from "@/services/ProjectCenter";
import { install } from 'element-ui';
export default {
  data () {
    return {
      selectedProArr: [],
      // 项目名称
      projectNameList: {
        value: {},
        //  label:'长兴山湖花园项目',
        options: [],
      },
      requestparam: {
        is_page: 1,
        pageNum: 1,
        pageSize: 10,
        projectId: "",
      },
      tableData: {
        list: [],
        total_count: 0,
      },
      // 编辑弹窗是否可见
      dialogVisible: false,
      editSchemeStatus: "create",
      title: "添加施工升降机",
      // 编辑方案数据对象
      editSchemeData: {
        projectName: "",
        deviceName: "",
        deviceNo: "",
        installationDate: "",
        projectId: "",
        elevatorId: "",
      },
      rules: {
        projectName: [
          { required: true, message: "请输入项目名称", trigger: "blur" },
        ],
        deviceName: [
          { required: true, message: "请输入设备名称", trigger: "blur" },
        ],
        deviceNo: [
          { required: true, message: "请输入设备编号", trigger: "blur" },
        ],
        installationDate: [
          { required: true, message: "请输入安装日期", trigger: "blur" },
        ],
      },
      disabled: true,
      view: false,
      userInfo: {},
      filterParams: {
        start_time: "",
        end_time: "",
        project_name: "",
      },
      dateRange: [], //日期
    };
  },
  methods: {
    getInstallDate (dateV) {//安装日期只显示年月日
      let moment = require("moment");
      let installDate = '';
      if (dateV) {//有值时执行
        installDate = moment(dateV).format('YYYY-MM-DD')
      }
      return installDate;
    },
    onRealTimeData (row) {//实时数据
      let proId = row.project_id;
      let deviceNo = row.device_no;
      this.$router.push({ path: 'realTimeDataPage', query: { project_id: proId, device_no: deviceNo } });
    },
    // 每页多少条
    handleSizeChange (val) {
      this.requestparam.pageSize = val;
      this.getConstructionList();
    },
    // 当前页
    handleCurrentChange (val) {
      this.requestparam.pageNum = val;
      this.getConstructionList();
    },
    // 获取数据列表
    getConstructionList () {
      this.requestparam.projectId = this.projectNameList.value.project_id || "";
      constructionLiftApi
        .getConstructionLift({
          params: {
            projectId: this.requestparam.projectId,
            pageNum: this.requestparam.pageNum,
            pageSize: this.requestparam.pageSize,
          },
        })
        .then(
          (res) => {
            if (res.code === 0) {
              console.log(res);
              this.tableData.list = res.data.list;
              console.log(this.tableData.list);
              this.tableData.total_count = res.data.total_count;
            }
          },
          (err) => {
            console.log(err);
          }
        );
    },
    editSchemeDialog (type, data) {
      this.editSchemeData.projectName = this.projectNameList.value.label;
      this.editSchemeData.projectId = this.projectNameList.value.project_id;
      this.editSchemeData.deviceName = data.device_name;
      this.editSchemeData.deviceNo = data.device_no;
      this.editSchemeData.installationDate = data.installation_date;
      this.editSchemeData.elevatorId = data.elevator_id;
      this.editSchemeStatus = type;
      if (type === "create") {
        this.title = "添加施工升降机";
        this.view = false;
      } else if (type === "edit") {
        this.title = "编辑";
        this.view = false;
      } else {
        this.title = "施工升降机详情";
        this.view = true;
      }

      console.log(this.editSchemeData);
      this.dialogVisible = true;
    },
    editScheme () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.editSchemeStatus === "create") {
            this.createScheme();
          } else if (this.editSchemeStatus === "edit") {
            this.updateScheme();
          } else {
            this.dialogVisible = false;
          }
        }
      });
    },
    // 点击新增
    createScheme () {
      let moment = require("moment");
      let t1 = moment(this.editSchemeData.installationDate).format(
        "YYYY-MM-DD HH:mm:ss"
      );
      this.editSchemeData.installationDate = t1;
      constructionLiftApi
        .getEditConstructionLift({
          data: this.editSchemeData,
        })
        .then(
          (res) => {
            if (res.code === 0) {
              this.open2();
              this.dialogVisible = false;
              this.getConstructionList();
            }
          },
          (err) => {
            console.log(err);
          }
        );
    },
    // 点击编辑
    updateScheme () {
      let moment = require("moment");
      let t1 = moment(this.editSchemeData.installationDate).format(
        "YYYY-MM-DD HH:mm:ss"
      );
      this.editSchemeData.installationDate = t1;
      console.log(this.editSchemeData);
      constructionLiftApi
        .getEditConstructionLift({
          data: this.editSchemeData,
        })
        .then(
          (res) => {
            if (res.code === 0) {
              this.open2();
              this.dialogVisible = false;
              this.getConstructionList();
            }
          },
          (err) => {
            console.log(err);
          }
        );
    },
    // 点击删除
    delet (row) {
      console.log(row);
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          constructionLiftApi
            .getDeleConstructionLift({
              params: {
                elevatorId: row.elevator_id,
              },
            })
            .then((res) => {
              if (res.code === 0) {
                this.$message({
                  type: "success",
                  message: "删除成功",
                });
                this.getConstructionList();
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    dialogClose () {
      this.$refs.ruleForm.resetFields();
    },
    selectProjectNameList (data) {
      this.projectNameList.value = data;
      this.getConstructionList();
    },
    getProArr (list) {//项目名称下拉数据
      list.map((item, index) => {
        this.projectNameList.options[index] = {
          label: item.project_name,
          value: index,
          project_id: item.project_id,
        };
      });
      this.projectNameList.value = JSON.parse(
        JSON.stringify(this.projectNameList.options[0])
      );
    },
    // // 获取项目列表
    // async getProjectList () {
    //   await ProjectListApi.getProjectManageList({
    //     data: {
    //       is_page: 0,
    //       conditions: [],
    //       module_id: "3",
    //     },
    //   }).then(
    //     (res) => {
    //       if (res.code === 0) {
    //         res.data.list.map((item, index) => {
    //           this.projectNameList.options[index] = {
    //             label: item.project_name,
    //             value: index,
    //             project_id: item.project_id,
    //           };
    //         });
    //         this.projectNameList.value = JSON.parse(
    //           JSON.stringify(this.projectNameList.options[0])
    //         );
    //       }
    //     },
    //     (err) => {
    //       console.log(err);
    //     }
    //   );
    // },
    // 成功提示
    open2 () {
      this.$message({
        message: "添加成功",
        type: "success",
      });
    },
    Cancel () {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) {
          if (this.editSchemeStatus === "create") {
            this.$message({
              message: "取消添加",
              type: "warning",
            });
          }
        } else if (this.editSchemeStatus === "edit") {
          this.$message({
            message: "取消编辑",
            type: "warning",
          });
        } else {
          this.dialogVisible = false;
        }
      });
      this.dialogVisible = false;
    },
  },
  watch: {
    '$store.state.choosedProject': {
      handler (newval) {
        this.project = newval
        // this.requestParams.project_id = this.project.project_id;
        if (this.$store.state.choosedProjectList.length == 0) {
          this.selectedProArr = [newval];//默认首个
          this.getProArr(this.selectedProArr);//获取项目下拉数据
        }
        this.getConstructionList();//刷新
      },
      deep: true,
      immediate: true
    },
    //飞轮项目切换时更新列表数据
    '$store.state.choosedProjectList': {
      handler (newval) {
        if (newval.list.length > 0) {
          this.selectedProArr = newval.list;
          this.getProArr(this.selectedProArr);//获取项目下拉数据
        };
        if (newval.list.length == 0) {
          let local = window.localStorage.getItem('choosedProject') || '{}'
          this.selectedProArr = [JSON.parse(local)] || [];
          this.getProArr(this.selectedProArr);//获取项目下拉数据
          // this.requestParams.project_id = this.selectedProArr[0].project_id || '';
        };
        this.getConstructionList();//模糊查询
      },
      deep: true
    },
  },
  mounted () {
    let local = window.localStorage.getItem('choosedProject') || '{}';
    let chooseList = window.localStorage.getItem('choosedProjectList') || '[]';
    if (JSON.parse(chooseList).length > 0) {
      this.selectedProArr = JSON.parse(chooseList);
    } else {
      this.selectedProArr = [JSON.parse(local)];
    };
    this.getProArr(this.selectedProArr);
    // this.getProjectList();
    setTimeout(() => {
      this.getConstructionList();
    }, 1000);
  },
};
</script>
<style lang="scss" scoped>
.construction {
  padding: 20px;
}
.select-style {
  width: 100% !important;
}
</style>
